﻿using System;

class SquareWithMaximalSum
{
    static void Main()
    {
        // test toni
        //Exercise 2.
        //Write a program that reads a rectangular matrix of size N x M and finds in it the square 3 x 3 that has 
        //maximal sum of its elements.

        //Declare the matrix
        Console.Write("Enter the matrix size N: ");
        int n = int.Parse(Console.ReadLine());
        Console.Write("Enter the matrix size M: ");
        int m = int.Parse(Console.ReadLine());
        int[,] matrix = new int[n, m];

        //Initialize the matrix from the console
        //for (int row = 0; row < n; row++)
        //{
        //    for (int col = 0; col < m; col++)
        //    {
        //        Console.Write("Matrix [{0},{1}]  ", row,col);
        //        matrix[row, col] = int.Parse(Console.ReadLine());
        //    }
        //}

        //Initialize the matrix using random
        Random random = new Random();
        for(int row = 0; row < n; row++)
        {
            for (int col = 0; col < m; col++)
			{
                matrix[row, col] =  random.Next(0, 100);			 
			}            
        }

        // Find the maximal sum square of size 3 x 3
        int bestSum = int.MinValue;
        int bestRow = 0;
        int bestCol = 0;

        for (int row = 0; row < matrix.GetLength(0) - 2; row++)
        {
            for (int col = 0; col < matrix.GetLength(1) - 2; col++)
            {
                int sum = matrix[row, col] + matrix[row + 1, col] + matrix[row + 2, col] +
                    matrix[row, col + 1] + matrix[row + 1, col + 1] + matrix[row + 2, col + 1] +
                    matrix[row, col + 2] + matrix[row + 1, col + 2] + matrix[row + 2, col + 2];
                if (sum > bestSum)
                {
                    bestSum = sum;
                    bestRow = row;
                    bestCol = col;
                }
            }
        }

        //Print the result
        Console.WriteLine("The square 3 x 3 with maximal sum of its elements: ");
        Console.WriteLine("  {0,3} {1,3} {2,3}",
            matrix[bestRow, bestCol],
            matrix[bestRow, bestCol + 1],
            matrix[bestRow, bestCol + 2]);
        Console.WriteLine("  {0,3} {1,3} {2,3}",
            matrix[bestRow + 1, bestCol],
            matrix[bestRow + 1, bestCol + 1],
            matrix[bestRow + 1, bestCol + 2]); 
        Console.WriteLine("  {0,3} {1,3} {2,3}",
             matrix[bestRow + 2, bestCol],
             matrix[bestRow + 2, bestCol + 1],
             matrix[bestRow + 2, bestCol + 2]);
        Console.WriteLine("The maximal sum is: {0}", bestSum);
        Console.WriteLine();
    }
}

